package ctrl.action.impl;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Model;
import model.beans.ItemBean;

import util.ProjectConstants;

import ctrl.action.ServletAction;

public class ItemServletAction implements ServletAction{
	
	private ServletContext context;	
	public ItemServletAction(ServletContext context) {
		this.context = context;
	}

	@Override
	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {

		String jsp;
		HttpSession session = request.getSession();
		String selectedItem = request.getParameter(ProjectConstants.PARAMITEMID);
		Model model = (Model) context.getAttribute(ProjectConstants.PARAMMODEL);
		ItemBean item = (ItemBean) model.getItemByNumber(selectedItem);
		request.setAttribute(ProjectConstants.PARAMITEM, item);

		//For returning page after login
		String previousPage = ProjectConstants.PARAMITEM + "?" + ProjectConstants.PARAMITEMID + "=" + selectedItem;
		session.setAttribute(ProjectConstants.PARAMPREVIOUSPAGE, previousPage);
		
		if(item != null){
			jsp = ProjectConstants.PAGEITEMDETAIL;
		}
		else{
			jsp = ProjectConstants.PAGEERROR;
		}
		
		context.getRequestDispatcher("/" + jsp + ".jspx").forward(request, response);	
	}
}
